#include "mainservice.h"
#include "widget.h"

#include <QApplication>
#include <QDateTime>
#include <QDir>
#include <QTextStream>

void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString logDataTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString logData = QDateTime::currentDateTime().toString("yyyy-MM-dd");

    QString logHead;
    QString message;
    switch (type)
    {
    case QtDebugMsg:
        logHead = QString("运行");
        message = QString("<a style='color:green;'>【%1 | %2】: %3</a>").arg(logHead).arg(logDataTime).arg(msg);
        break;
    case QtWarningMsg:
        logHead = QString("警告");
        message = QString("<a style='color:yellow;'>【%1 | %2】: %3</a>").arg(logHead).arg(logDataTime).arg(msg);
        break;
    case QtCriticalMsg:
        logHead = QString("严重");
        message = QString("<a style='color:red;'>【%1 | %2】: %3</a>").arg(logHead).arg(logDataTime).arg(msg);
        break;
    case QtFatalMsg:
        logHead = QString("致命");
        message = QString("<a style='color:red;'>【%1 | %2】: %3</a>").arg(logHead).arg(logDataTime).arg(msg);
    }
    QString logDirPath = qApp->applicationDirPath() + "/logs/";
    if (!QDir().exists(logDirPath))
    {
        QDir().mkpath(logDirPath);
    }
    QString logPath = QString(qApp->applicationDirPath() + "/logs/" + logData + "_log.html");

    QFile file(logPath);
    file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
    QTextStream text_stream(&file);
    text_stream.setCodec("utf-8");
    text_stream << message << "<br/>";
    file.flush();
    file.close();
}

int main(int argc, char *argv[])
{
    if (argc > 1 && std::string(argv[1]) == "-a")
    {
        QApplication a(argc, argv);
        // 安装日志
#ifndef QT_DEBUG
        // qInstallMessageHandler(outputMessage);
#endif
        Widget w;
        w.show();
        return a.exec();
    }
    else
    {
        MainService service(argc, argv);
        // 安装日志
#ifndef QT_DEBUG
        // qInstallMessageHandler(outputMessage);
#endif
        return service.exec();
    }
}
